package com.atguigu.tingshu;

import org.junit.jupiter.api.Test;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.concurrent.TimeUnit;

/**
 * @author: atguigu
 * @create: 2024-10-30 10:17
 */
@SpringBootTest
public class RedissonLock {


    @Autowired
    private RedissonClient redissonClient;


    @Test
    public void testLock() {
        //1.创建锁对象 入参锁名称
        RLock myLock = redissonClient.getLock("myLock");
        //2.获取分布式锁
        myLock.lock(); //默认锁过期时间：30s
        //3.加锁成功后执行业务逻辑
        try {
            System.out.println("获取锁成功执行业务逻辑...");
            TimeUnit.SECONDS.sleep(100);

            myLock.lock();
            System.out.println("可重入后再次执行其他业务");
            myLock.unlock();
            //底层再次将锁时间设置为30s

            System.out.println("继续执行业务");
            System.out.println("继续执行业务");
            System.out.println("继续执行业务");
            System.out.println("继续执行业务");

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //4.释放锁
            myLock.unlock();
        }

    }

}
